import http from './request.js';

class StudentProfiles {
    constructor() {
        this.searchInput = document.getElementById('searchInput');
        this.searchButton = document.getElementById('searchButton');
        this.studentTable = document.getElementById('studentTable').getElementsByTagName('tbody')[0];
        this.profileContainer = document.getElementById('profileContainer');
        
        this.currentPage = 1;
        this.loading = false;
        this.hasMore = true;
        this.lastKeyword = '';

        this.init();
    }

    init() {
        this.loadStudents();
        this.bindEvents();
    }

    bindEvents() {
        // Search button click event
        this.searchButton.addEventListener('click', () => {
            this.handleSearch();
        });

        // Search input box Enter key event
        this.searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.handleSearch();
            }
        });

        // Listen for scroll events
        this.profileContainer.addEventListener('scroll', () => {
            this.handleScroll();
        });
    }

    // Handle scroll loading
    handleScroll() {
        if (this.loading || !this.hasMore) return;

        const { scrollTop, scrollHeight, clientHeight } = this.profileContainer;
        // Start loading when 100px from the bottom
        if (scrollHeight - scrollTop - clientHeight < 100) {
            this.currentPage++;
            this.loadStudents(this.lastKeyword, true);
        }
    }

    // Load student list
    async loadStudents(keyword = '', append = false) {
        if (this.loading) return;
        
        try {
            this.loading = true;
            
            // If not append mode, reset page number and list
            if (!append) {
                this.currentPage = 1;
                this.studentTable.innerHTML = '';
            }

            const response = await http.get(`/students/page/${this.currentPage}`, {
                keyword: keyword
            });
            
            console.log('Received response:', response);
            
            const students = response.list || [];
            this.hasMore = students.length === response.limit; // If the number of returned data is equal to the limit, it may mean there are more
            this.lastKeyword = keyword;

            if (append) {
                this.appendStudents(students);
            } else {
                this.renderStudents(students);
            }
        } catch (error) {
            console.error('Failed to load students:', error);
            alert('Failed to load student list: ' + error.message);
        } finally {
            this.loading = false;
        }
    }

    // Handle search
    async handleSearch() {
        const keyword = this.searchInput.value.trim();
        await this.loadStudents(keyword);
    }

    // Render student list
    renderStudents(students) {
        if (!Array.isArray(students)) {
            console.error('Invalid students data:', students);
            return;
        }
        
        this.studentTable.innerHTML = this.generateStudentRows(students);

        if (students.length === 0) {
            this.studentTable.innerHTML = `
                <tr>
                    <td colspan="7" style="text-align: center;">No students found</td>
                </tr>
            `;
        }
    }

    // Append student list
    appendStudents(students) {
        if (!Array.isArray(students) || students.length === 0) return;
        
        const newRows = this.generateStudentRows(students);
        this.studentTable.insertAdjacentHTML('beforeend', newRows);
    }

    // Generate student row HTML
    generateStudentRows(students) {
        return students.map(student => `
            <tr>
                <td>
                    <img src="${student.Photo || '../assets/images/default_photo.jpg'}" 
                         alt="Student Photo" 
                         class="student-photo">
                </td>
                <td>${student.Name || '-'}</td>
                <td>${student.Email || '-'}</td>
                <td>${this.formatList(student.Interests)}</td>
                <td>${this.formatList(student.Courses)}</td>
                <td>${this.formatList(student.Achievements)}</td>
                <td>${student.Bio || '-'}</td>
            </tr>
        `).join('');
    }

    // Format list display
    formatList(str) {
        if (!str) return '-';
        return str.split(',')
            .map(item => `<span class="tag">${item.trim()}</span>`)
            .join('');
    }
}

// Initialize student list page
new StudentProfiles(); 